package com.fm.financemanage.component;

import com.alibaba.fastjson.JSONObject;


import com.fm.financemanage.constant.UserConstants;
import com.fm.financemanage.exception.BusinessException;
import com.fm.financemanage.mapper.AccountantMapper;
import com.fm.financemanage.model.po.Accountant;
import com.fm.financemanage.model.po.SysUser;
import com.fm.financemanage.model.vo.SysUserVo;
import com.fm.financemanage.model.vo.UserInfoVo;
import com.fm.financemanage.model.vo.UserTokenVo;
import com.fm.financemanage.utils.AESUtil;
import com.fm.financemanage.utils.TextUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author zpc
 * @version V1.0
 * @date
 */
@Component
public class TokenComponent {

    @Value("${aes.secret}")
    private String secret;

    @Resource
    private AccountantMapper accountantMapper;


    /**
     * 生成用户的token
     *
     * @param token
     * @return
     */
    public SysUser getByToken(String token) {
        try {
            if (!TextUtil.isEmpty(token)) {
                String data = AESUtil.decryptHex(token, secret);
                return JSONObject.parseObject(data, SysUser.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 生成用户的token
     *
     * @param token
     * @return
     */
    public SysUserVo getVoByToken(String token) {
        try {
            if (!TextUtil.isEmpty(token)) {
                String data = AESUtil.decryptHex(token, secret);
                return JSONObject.parseObject(data, SysUserVo.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成用户的token
     *
     * @param userInfoVo
     * @return
     */
    public String getByUser(UserInfoVo userInfoVo) {
        try {
            if (!TextUtil.isEmpty(userInfoVo)) {
                String s = JSONObject.toJSONString(userInfoVo.getUserTokenVo());
                return AESUtil.encryptHex(s, secret);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public UserTokenVo getMember(String token) {

        if (!TextUtil.isEmpty(token)) {
            String data = AESUtil.decryptHex(token, secret);
            if (TextUtil.isEmpty(data)) {
                System.out.println("错误token：" + token);
                throw new BusinessException("token异常");
            }

            return JSONObject.parseObject(data, UserTokenVo.class);
        }

        return null;
    }

}
